<template>
  <div class="farmer-profile">
    <el-row :gutter="24">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="profile-header">
            <div class="avatar-container">
              <el-upload
                class="avatar-uploader"
                :http-request="customUpload"
                :show-file-list="false"
                accept="image/jpeg,image/png"
              >
                <img
                  v-if="formData.avatar"
                  :src="formData.avatar"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </div>
            <h2 class="username">{{ userInfo.userName }}</h2>
            <div class="role-tag">
              <el-tag type="success">认证农户</el-tag>
            </div>
          </div>

          <div class="profile-stats">
            <div class="stat-item">
              <span class="stat-value">{{ statistics.productCount || 0 }}</span>
              <span class="stat-label">在售商品</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{
                statistics.orderTotalCount || 0
              }}</span>
              <span class="stat-label">总订单</span>
            </div>
            <div class="stat-item">
              <span class="stat-value"
                >¥{{ (statistics.totalSales || 0).toFixed(2) }}</span
              >
              <span class="stat-label">总销售额</span>
            </div>
          </div>

          <div class="info-list">
            <div class="info-item">
              <el-icon><Timer /></el-icon>
              <span class="label">注册时间：</span>
              <span>{{ formatDate(userInfo.createdTime) }}</span>
            </div>
            <div class="info-item">
              <el-icon><Phone /></el-icon>
              <span class="label">联系电话：</span>
              <span>{{ formatPhone(userInfo.phone) }}</span>
            </div>
            <div class="info-item">
              <el-icon><Message /></el-icon>
              <span class="label">电子邮箱：</span>
              <span>{{ userInfo.email || "未设置" }}</span>
            </div>
            <div class="info-item">
              <el-icon><User /></el-icon>
              <span class="label">性别：</span>
              <span>{{ formatGender(userInfo.sex) }}</span>
            </div>
          </div>
        </el-card>

        <!-- 账户安全卡片 -->
        <el-card class="security-card">
          <template #header>
            <div class="card-header">
              <span>账户安全</span>
            </div>
          </template>
          <div class="security-items">
            <div class="security-item">
              <div class="security-info">
                <el-icon><Lock /></el-icon>
                <span>登录密码</span>
              </div>
              <el-button link type="primary">修改</el-button>
            </div>
            <div class="security-item">
              <div class="security-info">
                <el-icon><Phone /></el-icon>
                <span>手机绑定</span>
              </div>
              <el-tag size="small" type="success">已绑定</el-tag>
            </div>
            <div class="security-item">
              <div class="security-info">
                <el-icon><Message /></el-icon>
                <span>邮箱绑定</span>
              </div>
              <el-button link type="primary">绑定</el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧信息编辑表单 -->
      <el-col :span="16">
        <el-card class="edit-form">
          <template #header>
            <div class="card-header">
              <span>个人信息设置</span>
              <el-button type="primary" @click="submitForm">保存修改</el-button>
            </div>
          </template>

          <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="userName">
                  <el-input
                    v-model="formData.userName"
                    placeholder="请输入用户名"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="昵称" prop="nickname">
                  <el-input
                    v-model="formData.nickname"
                    placeholder="请输入昵称"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input
                    :model-value="formatPhone(formData.phone)"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电子邮箱" prop="email">
                  <el-input
                    v-model="formData.email"
                    placeholder="请输入电子邮箱"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="formData.sex">
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="个人简介" prop="introduce">
              <el-input
                v-model="formData.introduce"
                type="textarea"
                :rows="4"
                placeholder="请输入个人简介"
              />
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 经营数据卡片 -->
        <el-card class="business-card">
          <template #header>
            <div class="card-header">
              <span>经营数据</span>
              <el-radio-group v-model="dateRange" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">本年</el-radio-button>
              </el-radio-group>
            </div>
          </template>

          <el-row :gutter="20" class="data-overview">
            <el-col :span="8">
              <div class="data-item">
                <div class="data-title">销售额</div>
                <div class="data-value">
                  ¥{{ (statistics.monthSales || 0).toFixed(2) }}
                </div>
                <div class="data-compare">
                  <span class="up">
                    <el-icon><ArrowUp /></el-icon>12.5%
                  </span>
                  较上期
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="data-item">
                <div class="data-title">订单数</div>
                <div class="data-value">
                  {{ statistics.orderTotalCount || 0 }}
                </div>
                <div class="data-compare">
                  <span class="up">
                    <el-icon><ArrowUp /></el-icon>8.2%
                  </span>
                  较上期
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="data-item">
                <div class="data-title">商品数</div>
                <div class="data-value">
                  {{ statistics.productTotalCount || 0 }}
                </div>
                <div class="data-compare">
                  <span class="down">
                    <el-icon><ArrowDown /></el-icon>3.1%
                  </span>
                  较上期
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import {
  Plus,
  Timer,
  Phone,
  Message,
  User,
  Lock,
  ArrowUp,
  ArrowDown,
} from "@element-plus/icons-vue";
import request from "@/utils/request";

// 定义用户信息
const userInfo = ref({
  avatar: "",
  userName: "",
  createdTime: "",
  phone: "",
  email: "",
  sex: 0,
});

const formData = reactive({
  userName: "",
  email: "",
  phone: "",
  sex: "",
  avatar: "",
  introduce: "",
  nickname: "",
});

const avatarInput = ref<HTMLInputElement | null>(null);

// 表单校验规则
const rules = {
  userName: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, message: "用户名长度不能小于2个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入电子邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
};

// 添加统计数据
const statistics = ref({
  productCount: 0,
  productTotalCount: 0,
  orderTotalCount: 0,
  totalSales: 0,
  monthSales: 0,
});

// 日期范围选择
const dateRange = ref("month");

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await request({
      url: "/user/rural/queryInfo",
      method: "get",
    });
    if (res.success && res.data) {
      // 格式化手机号码和处理数据
      const formattedData = {
        ...res.data,
        phone: "18*******00", // 直接使用固定格式
        sex: Number(res.data.sex), // 确保sex是数字类型
      };
      userInfo.value = formattedData;
      formData.userName = formattedData.userName || "";
      formData.email = formattedData.email || "";
      formData.phone = formattedData.phone;
      formData.sex = formattedData.sex; // 直接使用数字，不需要转字符串
      formData.avatar = formattedData.avatar || "";
      formData.introduce = formattedData.introduce || "";
      formData.nickname = formattedData.nickname || "";
    } else {
      console.error("获取用户信息失败: 返回数据为空");
      ElMessage.error("获取用户信息失败");
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败");
  }
};

// 获取统计数据
const getStatistics = async () => {
  try {
    const res = await request({
      url: "/user/rural/show/totalCount",
      method: "get",
    });
    if (res.success) {
      statistics.value = res.data;
    }
  } catch (error) {
    console.error("获取统计数据失败:", error);
  }
};

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return "未设置";
  return new Date(date).toLocaleDateString();
};

// 格式化性别
const formatGender = (sex: number) => {
  if (sex === 1) return "男";
  if (sex === 2) return "女";
  return "未设置";
};

// 处理头像上传
const customUpload = async (options: any) => {
  const file = options.file;

  // 验证文件
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error("头像只能是 JPG 或 PNG 格式!");
    return;
  }
  if (!isLt2M) {
    ElMessage.error("头像大小不能超过 2MB!");
    return;
  }

  // 创建上传用的 FormData（注意这里改名为 uploadData 以避免混淆）
  const uploadData = new FormData();
  uploadData.append("uploadFile", file);

  try {
    const res = await request({
      url: "/file/ali/upload",
      method: "post",
      data: uploadData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });

    if (res.success) {
      // 直接更新组件的 formData.avatar
      formData.avatar = res.data;
      ElMessage.success("头像上传成功");
    }
  } catch (error) {
    console.error("上传失败:", error);
    ElMessage.error("头像上传失败");
  }
};

// 提交个人信息修改
const submitForm = async () => {
  try {
    // 确保包含所有需要更新的字段
    const params = {
      userName: formData.userName,
      email: formData.email,
      sex: Number(formData.sex),
      avatar: formData.avatar, // 确保包含头像URL
      introduce: formData.introduce,
      nickname: formData.nickname,
    };

    const res = await request({
      url: "/user/rural/updateInfo",
      method: "post",
      data: params,
    });

    if (res.success) {
      ElMessage.success("保存成功");
      getUserInfo();
    }
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
  }
};

// 触发文件选择
const triggerAvatarInput = () => {
  avatarInput.value?.click();
};

// 格式化手机号
const formatPhone = (phone: string) => {
  if (!phone) return "未设置";
  return phone.replace(/(\d{2})\d{7}(\d{2})/, "$1*******$2");
};

onMounted(() => {
  getUserInfo();
  getStatistics();
});
</script>

<style lang="scss" scoped>
.farmer-profile {
  padding: 20px;

  .profile-card {
    margin-bottom: 20px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .profile-header {
      text-align: center;
      padding: 24px 0;

      .avatar-container {
        margin-bottom: 16px;
      }

      .username {
        margin: 12px 0 8px;
        font-size: 20px;
        font-weight: 600;
        color: #333;
      }

      .role-tag {
        margin-top: 8px;
      }
    }

    .profile-stats {
      display: flex;
      justify-content: space-around;
      padding: 20px 0;
      border-top: 1px solid #f0f0f0;
      border-bottom: 1px solid #f0f0f0;
      margin: 0 -20px 20px;

      .stat-item {
        text-align: center;

        .stat-value {
          font-size: 20px;
          font-weight: 600;
          color: #333;
          line-height: 1.5;
        }

        .stat-label {
          font-size: 13px;
          color: #909399;
        }
      }
    }

    .info-list {
      padding: 0 12px;

      .info-item {
        display: flex;
        align-items: center;
        margin-bottom: 16px;
        font-size: 14px;

        .el-icon {
          margin-right: 8px;
          font-size: 16px;
          color: #909399;
        }

        .label {
          color: #909399;
          margin-right: 8px;
        }
      }
    }
  }

  .security-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .security-items {
      .security-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .security-info {
          display: flex;
          align-items: center;

          .el-icon {
            margin-right: 8px;
            font-size: 16px;
            color: #909399;
          }
        }
      }
    }
  }

  .edit-form {
    margin-bottom: 20px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      span {
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }
    }
  }

  .business-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .data-overview {
      padding: 20px 0;

      .data-item {
        padding: 20px;
        background: #f8f9fa;
        border-radius: 8px;

        .data-title {
          font-size: 14px;
          color: #909399;
          margin-bottom: 12px;
        }

        .data-value {
          font-size: 24px;
          font-weight: 600;
          color: #333;
          margin-bottom: 12px;
        }

        .data-compare {
          font-size: 13px;
          color: #909399;

          .up {
            color: #67c23a;
          }

          .down {
            color: #f56c6c;
          }

          .el-icon {
            margin-right: 4px;
          }
        }
      }
    }
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 50%;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: all 0.3s;

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: block;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style> 